import { NextResponse, type NextRequest } from 'next/server'; import { getCustomerUser } from '@/app/lib/lumen-auth'; import { commerceDb } from '@/app/lib/commerce-db'; import { isAdmin } from '@/app/lib/admin'; import { generateImage, fetchReference, buildCustomerRevisionPrompt, buildRefinePrompt, buildChainRefinePrompt, aspectSpecFromFrame, withAspect } from '@/app/lib/image-gen'; import { OPENAI_IMAGE_MODEL, resolveImageModel, SUPPORTED_MODELS, type ImageModel } from '@/app/lib/image-models'; import { cropToAspect } from '@/app/lib/image-crop'; import { downloadOriginalImage, uploadImage } from '@/app/lib/cf-images'; import { frameAspect, type ProductId, type Orientation } from '@/app/lib/pricing'; import { activeProofRevision, customerRevisions, orderMessageConfig, ORDER_MESSAGE_LIMIT, type PrintUpscale } from '@/app/lib/order-messages'; import { prepareWiderFraming, requestsWiderFraming } from '@/app/lib/revision-framing'; import { encodePhotoJpeg, imageDimensions, upscalePrintImage } from '@/app/lib/image-processing'; export const runtime = 'nodejs'; export const dynamic = 'force-dynamic'; export const maxDuration = 120; const PRINT_LONG_EDGE = 4096; /** Encode a generated master as a high-quality JPEG for upload. Raw 4K * PNGs routinely exceed Cloudflare Images' 20 MB ceiling (multi-pet * renders are the most detailed → largest), which fails the upload. * q90 mozjpeg keeps the full 4K resolution for print while landing at a * few MB. These are opaque photographic prints, so PNG's losslessness / * alpha buys nothing here; flatten any stray alpha onto white. */ async function toUploadJpeg(bytes: Buffer): Promise { return encodePhotoJpeg(bytes, 90); } /** Shared post-processing tail for every generation path (fresh, refine, * chain): crop the AI's square output to the customer's frame aspect, * upload the clean file, and insert a generations row. Returns the inserted gen or throws. */ async function finalizeGeneration(args: { admin: ReturnType; orderId: string; model: string; prompt: string; rawBytes: Buffer; targetAspect: string | null; setStage: (stage: string) => void; printSize?: PrintUpscale['upscaled']; }) { const { admin, orderId, model, prompt, rawBytes, targetAspect, setStage, printSize } = args; setStage('prepare preview'); // Crop the AI's square output to the customer's frame aspect so the // stored file (which Prodigi prints) matches what they'll receive. // No-op if aspect already matches. Proofs are shown clean: there is no // watermark, so the customer sees exactly the artwork we print. const cleanBytes = targetAspect ? await cropToAspect(rawBytes, targetAspect) : rawBytes; // Encode to JPEG before upload — a 4K PNG can exceed CF Images' 20 MB // limit. JPEG preserves the full 4K resolution at a fraction of the size. const cleanJpeg = await toUploadJpeg(cleanBytes); setStage('upload images'); const clean = await uploadImage(cleanJpeg, { filename: `${orderId}-clean.jpg`, metadata: { kind: 'generation_clean', order: orderId } }); if (printSize) { setStage('verify delivered print resolution'); const delivered = await fetchReference(clean.printUrl); const { width, height } = await imageDimensions(delivered.bytes); if (width !== printSize.width || height !== printSize.height) { throw new Error('The print file did not retain the enlarged dimensions in delivery. Your draft is still available.'); } } setStage('save render'); const { data: gen, error: insErr } = await admin .from('generations') .insert({ order_id: orderId, prompt, model, clean_url: printSize ? clean.printUrl : clean.publicUrl, // Legacy column: now the clean preview URL (no watermark). watermarked_url: clean.publicUrl, published: false, }) .select('id, clean_url, watermarked_url, created_at, model') .single(); if (insErr || !gen) throw new Error(`db insert failed: ${insErr?.message}`); return gen; } async function saveRevisionDraft( admin: ReturnType, orderId: string, baseGenerationId: string, feedbackAt: string, generationId: string, replaceDraftId: string | null, printUpscale?: Omit, ) { // Chat replies also write order config. Re-read after generation and use // the existing optimistic update so those replies are preserved. for (let attempt = 0; attempt < 3; attempt += 1) { const { data: order, error } = await admin.from('orders') .select('status, current_generation_id, config, revision_note, updated_at').eq('id', orderId).single(); if (error || !order) throw new Error('Could not save the revision draft.'); const revision = activeProofRevision(order); if (revision?.baseGenerationId !== baseGenerationId || revision.feedback.at !== feedbackAt) return null; if (printUpscale && revision.draftId !== replaceDraftId) return null; if (printUpscale && revision.printUpscale) return revision.printUpscale.generationId; if (revision.draftId !== replaceDraftId) return revision.draftId; const { data: saved, error: saveError } = await admin.from('orders').update({ config: { ...orderMessageConfig(order.config), revisions: customerRevisions(order.config, order.revision_note, order.updated_at), revisionDraft: { generationId: printUpscale ? revision.draftId! : generationId, baseGenerationId, feedbackAt, ...(printUpscale ? { printUpscale: { ...printUpscale, generationId } } : {}), }, }, }).eq('id', orderId).eq('status', order.status).eq('current_generation_id', baseGenerationId) .eq('updated_at', order.updated_at).select('id').maybeSingle(); if (saveError) throw new Error('Could not save the revision draft.'); if (saved) return generationId; } return null; } export async function POST( req: NextRequest, ctx: { params: Promise<{ id: string }> }, ) { const { id } = await ctx.params; const incomingId = req.headers.get('x-generation-attempt'); const attemptId = incomingId && /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(incomingId) ? incomingId : crypto.randomUUID(); const startedAt = Date.now(); const reject = (error: string, status: number, reason: string) => { console.warn('[portrait generation] request rejected', { attemptId, status, reason }); return NextResponse.json({ error, attemptId }, { status }); }; const user = await getCustomerUser(); if (!user || !isAdmin(user.email)) { return reject('Your studio session is missing or expired. Sign in again and retry.', 403, 'not authorized'); } let body: { model?: unknown; prompt?: unknown; baseGenerationId?: unknown; finish?: unknown; upscale?: unknown; feedbackAt?: unknown; replaceDraftId?: unknown } | null; try { body = await req.json(); } catch { return reject('Invalid generation request.', 400, 'invalid json'); } const model = resolveImageModel(body?.model); if (!model) { return reject(`Select a supported model: ${SUPPORTED_MODELS.join(', ')}.`, 400, 'unsupported model'); } const prompt = typeof body?.prompt === 'string' ? body.prompt.trim() : ''; // Refine + finish both steer on a PRIOR generation instead of the pet // photo. The reference becomes that render's clean file. // • Refine: `prompt` is the admin's tweak ("same but red background"), // wrapped into an edit instruction; runs on the chosen model. // • Finish: re-render the existing image through OpenAI // to tighten the finish ("make one like this"). Supplies its own // prompt, so no user text is required. const baseGenerationId = typeof body?.baseGenerationId === 'string' ? body.baseGenerationId : null; const feedbackAt = body?.feedbackAt; const replaceDraftId = typeof body?.replaceDraftId === 'string' ? body.replaceDraftId : null; const finish = body?.finish === true; const upscale = body?.upscale === true; if (upscale && (typeof feedbackAt !== 'string' || !replaceDraftId || finish)) { return reject('Select a revision draft to upscale.', 400, 'missing upscale draft'); } if (feedbackAt !== undefined && (typeof feedbackAt !== 'string' || !baseGenerationId || finish || prompt.length > ORDER_MESSAGE_LIMIT)) { return reject('Select the current proof and customer feedback.', 400, 'invalid revision'); } if (finish && !baseGenerationId) { return reject('Select a render to finish.', 400, 'finish missing base'); } // Fresh + refine need a prompt; finish builds its own. if (!finish && !prompt && feedbackAt === undefined) return reject('Enter a prompt to generate.', 400, 'missing prompt'); console.info('[portrait generation] started', { attemptId, model, action: upscale ? 'upscale' : finish ? 'finish' : baseGenerationId ? 'refine' : 'generate' }); const admin = commerceDb(); const { data: order, error: orderErr } = await admin .from('orders') .select('id, pet_photo_urls, custom_style_url, config, status, current_generation_id, revision_note, updated_at') .eq('id', id) .single(); if (orderErr || !order) return reject('Could not load the order.', orderErr && orderErr.code !== 'PGRST116' ? 500 : 404, orderErr?.code ?? 'missing order'); const revision = feedbackAt === undefined ? null : activeProofRevision(order); if (feedbackAt !== undefined && (!revision || revision.baseGenerationId !== baseGenerationId || revision.feedback.at !== feedbackAt)) { return reject('The proof or customer feedback changed. Reopen the order and try again.', 409, 'stale revision'); } if (revision && replaceDraftId && revision.draftId !== replaceDraftId) { return reject('The draft changed. Review the latest draft before generating again.', 409, 'stale draft'); } if (upscale && revision?.printUpscale) return NextResponse.json({ generation: { id: revision.printUpscale.generationId }, attemptId }); if (revision?.draftId && !replaceDraftId) return NextResponse.json({ generation: { id: revision.draftId }, attemptId }); // Resolve the customer's chosen frame aspect from the order config. // We crop the AI output to this aspect so the file Prodigi prints // is exactly what the customer previewed inside their frame mock. const cfg = (order.config ?? {}) as { productId?: ProductId; size?: string; orientation?: Orientation; pets?: Array<{ slot?: number; name?: string }> }; // Landscape orders transpose the size's aspect — the crop + native // generation shape follow the orientation the customer chose. const targetAspect = frameAspect(cfg.productId, cfg.size, cfg.orientation ?? 'portrait'); // Generate natively in the frame's shape (model config below) and crop // to the exact frame aspect afterward. aspectSpec snaps the frame ratio // to the nearest each model supports. const aspectSpec = aspectSpecFromFrame(targetAspect); let stage = 'load references'; const setStage = (value: string) => { stage = value; console.info('[portrait generation] stage', { attemptId, stage, elapsedMs: Date.now() - startedAt }); }; try { if (upscale && revision?.draftId) { const { data: draft, error: draftError } = await admin.from('generations') .select('clean_url, model').eq('id', revision.draftId).eq('order_id', id).single(); if (draftError || !draft?.clean_url) return reject('The revision draft could not be loaded.', 404, 'missing upscale source'); setStage('load full-resolution draft'); const source = await downloadOriginalImage(draft.clean_url); const { width, height } = await imageDimensions(source); if (!width || !height) throw new Error('Could not read the draft image dimensions.'); if (Math.max(width, height) >= PRINT_LONG_EDGE) { return reject(`The revision draft is already ${width} × ${height} px. It meets the 4,096 px print target.`, 422, 'already print size'); } setStage('upscale print image'); const result = await upscalePrintImage(source, { width, height }, PRINT_LONG_EDGE); const original = { width, height }; const upscaled = { width: result.info.width, height: result.info.height }; const generation = await finalizeGeneration({ admin, orderId: id, model: draft.model, rawBytes: result.data, targetAspect: null, printSize: upscaled, setStage, prompt: `Print upscale: ${width} × ${height} px to ${upscaled.width} × ${upscaled.height} px. Source draft: ${revision.draftId}.`, }); const draftId = await saveRevisionDraft(admin, id, revision.baseGenerationId, revision.feedback.at, generation.id, revision.draftId, { original, upscaled }); if (!draftId) return reject('The revision draft changed while upscaling.', 409, 'upscale source changed'); return NextResponse.json({ generation: { id: draftId }, attemptId }); } // ── Resolve the reference image, model, and prompt for this pass ── let ref: { bytes: Buffer; mime: 'image/png' | 'image/jpeg' }; let additionalSubjectRefs: Array<{ bytes: Buffer; mime: 'image/png' | 'image/jpeg' }> = []; let subjectLabels: string[] = []; let styleRef: { bytes: Buffer; mime: 'image/png' | 'image/jpeg' } | null = null; let genModel: ImageModel = model; let genPrompt = prompt; let storedModel: string = model; if (baseGenerationId) { // Refine + finish steer on a prior render — the reference is that // generation's clean file. No custom-style ref on this path. const { data: baseGen, error: baseErr } = await admin .from('generations') .select('id, clean_url, model') .eq('id', baseGenerationId) .eq('order_id', order.id) .single(); if (baseErr || !baseGen?.clean_url) { return reject('The selected render could not be loaded.', baseErr && baseErr.code !== 'PGRST116' ? 500 : 404, baseErr?.code ?? 'missing base render'); } ref = await fetchReference(baseGen.clean_url); if (finish) { // Use the current OpenAI model with the route's OpenAI output size. // Keep the source model in the label so the history shows both passes. genModel = OPENAI_IMAGE_MODEL; genPrompt = withAspect(buildChainRefinePrompt(), aspectSpec); storedModel = baseGen.model ? `${baseGen.model}→${genModel}` : genModel; } else { // Refine: the admin's tweak, wrapped into an edit instruction // (+ frame-aspect directive), on the same engine that produced // the render. if (revision) { genModel = resolveImageModel(baseGen.model) ?? OPENAI_IMAGE_MODEL; storedModel = genModel; const widerFraming = (order.pet_photo_urls?.length ?? 0) <= 1 && requestsWiderFraming(revision.feedback.note); if (widerFraming) { ref = { bytes: await prepareWiderFraming(ref.bytes), mime: 'image/jpeg' }; } genPrompt = buildCustomerRevisionPrompt(revision.feedback.note, prompt, aspectSpec, widerFraming); } else { genPrompt = withAspect(buildRefinePrompt(prompt), aspectSpec); } } } else { // Fresh mode: subject pet photo(s) + (custom-style commissions) the // customer-uploaded style ref, fetched in parallel. EVERY uploaded // pet photo feeds the model so it composites them into one portrait // — the customer paid per pet, and the prompt's multi-pet language // only does anything if all the pets actually reach the model. // Gemini gets the style ref as the final positional reference; // OpenAI ignores it. const photos = (order.pet_photo_urls as string[]) ?? []; if (photos.length === 0) return reject('This order has no reference photo.', 400, 'missing reference photo'); // Best-effort pet names (positional) to label each subject in the // reference header — blank entries fall back to a generic label. // Upload order is preserved so image 1 is pet 1. const petNames = (cfg.pets ?? []).map(p => (p?.name ?? '').trim()); subjectLabels = photos.map((_, i) => petNames[i] ?? ''); const customStyleUrl = (order.custom_style_url as string | null) ?? null; const [subjectRefs, s] = await Promise.all([ Promise.all(photos.map(p => fetchReference(p))), customStyleUrl ? fetchReference(customStyleUrl) : Promise.resolve(null), ]); ref = subjectRefs[0]; additionalSubjectRefs = subjectRefs.slice(1); styleRef = s; } // Use the same render for the proof preview and the print file. setStage('generate image'); const rawBytes = await generateImage({ model: genModel, prompt: genPrompt, referenceBytes: ref.bytes, referenceMime: ref.mime, additionalSubjectReferences: additionalSubjectRefs, subjectLabels, styleReferenceBytes: styleRef?.bytes, styleReferenceMime: styleRef?.mime, // Frame-shape-aware: Gemini uses aspectRatio, OpenAI uses size. aspectRatio: aspectSpec.gemini, size: aspectSpec.openaiSize, geminiImageSize: '4K', }); const gen = await finalizeGeneration({ admin, orderId: order.id, model: storedModel, prompt: genPrompt, rawBytes, targetAspect, setStage, }); console.info('[portrait generation] saved', { attemptId, model: storedModel, generationId: gen.id, elapsedMs: Date.now() - startedAt }); if (!revision) return NextResponse.json({ generation: gen, attemptId }); const draftId = await saveRevisionDraft(admin, order.id, revision.baseGenerationId, revision.feedback.at, gen.id, replaceDraftId); if (!draftId) return reject('The proof changed while the revision rendered. Reload the order to review its latest state.', 409, 'revision changed while rendering'); return NextResponse.json({ generation: { id: draftId }, attemptId }); } catch (e) { const msg = e instanceof Error ? e.message : String(e); console.error('[portrait generation] failed', { attemptId, model, stage, elapsedMs: Date.now() - startedAt, errorType: e instanceof Error ? e.name : 'Unknown' }); return NextResponse.json({ error: msg, attemptId }, { status: 500 }); } }